package com.bsy.network.interceptor

import com.bsy.framework.ext.md5
import okhttp3.*
import java.io.IOException
import kotlin.math.abs
import kotlin.random.Random


/**
 * Created by Sincerity on 2024/3/7.
 * Copyright
 * 描述：
 */
class PublicBodyInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        // 获取原始的请求体
        val originalRequest = chain.request()
        val timestamp = System.currentTimeMillis().toString()
        val nonceStr = generateNonceStr()
        val modifiedUrl = originalRequest.url.newBuilder()
            .addQueryParameter("loginType", "android")
            .addQueryParameter("nonce_str", nonceStr)
            .addQueryParameter("timestamp", timestamp)
            .addQueryParameter("secret", hexMD5(timestamp, nonceStr))
            .build()
        val modifiedRequest = originalRequest.newBuilder()
            .url(modifiedUrl)
            .build()
        return chain.proceed(modifiedRequest)
    }

    private fun hexMD5(timestamp: String, nonceStr: String): String {
        val str = "productId=product_xc&token=fxQipHk3pZa0q5i9MxBlwO1bhM&nonce_str=$nonceStr&timestamp=$timestamp"
        return str.md5()
    }

    private fun generateNonceStr(): String {
        // 生成一个随机数，并将其转换为 36 进制的字符串
        var nonceStr = abs(Random.nextLong()).toString(36)
        // 确保随机字符串的长度至少为 15 个字符
        while (nonceStr.length < 15) {
            nonceStr = "0$nonceStr"  // 在字符串前添加字符 '0'
        }
        // 获取子字符串（从索引 2 开始，到索引 17 结束，总共 15 个字符）
        return nonceStr.substring(2, 15)
    }
}